package com.xingkeduo.business.order.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xingkeduo.pojo.query.IdGenerateMapper;
import com.xingkeduo.pojo.table.IdGenerate;
import com.xingkeduo.utils.RandomUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author chi  2019-03-19 10:40
 **/
@Service

public class IdGenerateService {

    @Resource
    private IdGenerateMapper idGenerateMapper;

    private ExecutorService executorService = Executors.newCachedThreadPool();


    public String get() {

        Future<String> submit = executorService.submit(() -> {
            IdGenerate idGenerate = idGenerateMapper.selectOne(new QueryWrapper<IdGenerate>().lambda().eq(IdGenerate::getType, 0).last("LIMIT 1"));

            if (idGenerate == null) {
                idGenerateMapper.restoreType();
                idGenerate = idGenerateMapper.selectOne(new QueryWrapper<IdGenerate>().lambda().eq(IdGenerate::getType, 0).last("LIMIT 1"));
            }

            int no = idGenerate.getNo();
            idGenerateMapper.updateById(idGenerate.setType(1));


            return String.format("%05d", no);
        });
        try {
            return submit.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return "";
    }

}
